import { sendCollection } from "./index.tsx";
import { CollectionType } from "./type";
let loopTimer: any = null;
const getWhiteScreen = function () {
  if (document.readyState == "complete") {
    sampling();
  } else {
    window.addEventListener("load", sampling);
  }
  // 定义外层容器元素的集合
  const containerElements = ["html", "body", "#app", "#root"];

  function getSelector(element) {
    if (element.id) {
      return "#" + element.id;
    } else if (element.className) {
      if (typeof element.className == "string") {
        return (
          "." +
          element.className
            .split(" ")
            .filter(item => !!item)
            .join(".")
        );
      } else {
        return element.className.toString();
      }
    } else {
      return element.nodeName.toLowerCase();
    }
  }
  function isContainer(element) {
    const selector = getSelector(element);
    return containerElements.indexOf(selector) != -1;
  }

  function sampling() {
    // 容器元素个数
    let emptyPoints = 0;
    for (let i = 1; i <= 9; i++) {
      const xElements = document.elementsFromPoint(
        (window.innerHeight * i) / 10,
        window.innerWidth / 2
      );
      const yElements = document.elementsFromPoint(
        window.innerWidth / 2,
        (window.innerHeight * i) / 10
      );
      if (isContainer(xElements[0])) emptyPoints++;
      if (i != 5) {
        if (isContainer(yElements[0])) emptyPoints++;
      }
    }
    if (emptyPoints != 17) {
      console.log(emptyPoints);
      return false;
    } else {
      /* 查询的点位都是空白点位 */
      if (!loopTimer) {
        timeWhiteLoop();
      }
      return true;
    }
  }

  function timeWhiteLoop() {
    const timeOutArr = [5, 10, 15, 20];
    const maxSecond = 20;
    function loop(curentloop) {
      if (curentloop > maxSecond) {
        loopTimer = null;
        return;
      }
      loopTimer = setTimeout(() => {
        if (sampling()) {
          /* 上报事件 */
          if (timeOutArr.includes(curentloop)) {
            sendCollection({
              type: CollectionType.PageWhite,
              pageUrl: location.href,
              stayDuration: curentloop * 1000
            });
          }
          loop(++curentloop);
        } else {
          loopTimer = null;
        }
      }, 1000);
    }
    loop(0);
  }
};

export { getWhiteScreen };
